package cz.muni.fi.pa165.rentalofconstructionmachineryweb.rest;

import cz.muni.fi.pa165.rentalofconstructionmachinery.dto.CustomerDTO;
import cz.muni.fi.pa165.rentalofconstructionmachinery.service.CustomerService;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 *
 * @author Adam Zmrzlý
 * @version Miura (20121312)
 */
@Controller
@RequestMapping("/customer")
public class CustomerController {
    
    @Autowired
    private CustomerService customerService;

    @RequestMapping(value = "/", method = RequestMethod.POST)
    public @ResponseBody CustomerDTO add(@RequestBody CustomerDTO customer, HttpServletRequest request, HttpServletResponse response) {
        customerService.addCustomer(customer);
        response.setStatus(HttpStatus.CREATED.value());
        response.setHeader("Location", request.getContextPath() + "/rest/customer/" + customer.getId());
 
        return customer;
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public @ResponseBody CustomerDTO get(@PathVariable("id") Long id) {
        return customerService.getCustomerById(id);
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public @ResponseBody CustomerDTO delete(@PathVariable("id") Long id, HttpServletResponse response) {
        CustomerDTO customer = customerService.getCustomerById(id);
        if (customer != null) {
            customerService.removeCustomer(customer);
        } else {
            throw new IllegalArgumentException("Customer not found.");
        }
       
        response.setStatus(HttpStatus.OK.value());
       
        return null;
    }
    
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public @ResponseBody CustomerDTO update(@PathVariable("id") Long id, @RequestBody CustomerDTO customer, HttpServletResponse response) {
        customer.setId(id);
        customerService.modifyCustomer(customer);
           
        response.setStatus(HttpStatus.OK.value());
        return customer;
    }
    
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public @ResponseBody List<CustomerDTO> getAll() {
        return customerService.getAllCustomers();
    }


}
